package com.yq.ylmall.activity.service.impl;

import com.yq.ylmall.constant.activity.PromotionConstants;
import com.yq.ylmall.model.activity.Coupon;
import com.yq.ylmall.model.activity.ExchangeCode;
import com.yq.ylmall.activity.mapper.ExchangeCodeMapper;
import com.yq.ylmall.activity.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yq.ylmall.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author cherry
 * @since 2024-06-13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {
    private final RedisTemplate<String,String> redisTemplate;
    @Override
    @Async("generateExchangeCodeExecutor") //使用自定义的线程池中的线程
    public void asyncGenerateExchangeCode(Coupon coupon) {
        log.info("生成兑换码 线程名{}",Thread.currentThread().getName());
        Integer totalNum = coupon.getTotalNum();
        //调用incyby 批量生成兑换码
        //生成自增id 借助于redis incr
        Long increment = redisTemplate.opsForValue().increment(PromotionConstants.COUPON_CODE_SERIAL_KEY, totalNum);
        if (increment == null)return;
        //本地自增id的最大值
        int maxSerialNum = increment.intValue();
        //自增id，循环开始值
        int begin = maxSerialNum - totalNum + 1;

        //循环生成兑换码 调用工具类生成兑换码
        List<ExchangeCode> list = new ArrayList<>();
        for (int serialNum = begin;serialNum<=maxSerialNum;serialNum++){
            //调用工具类生成兑换码 参数1：自增id值，参数2：优惠卷id（内部会计算0-15之间的下标中的一个获取密钥）
            String code = CodeUtil.generateCode(serialNum, coupon.getId());
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setId(serialNum);
            exchangeCode.setCode(code);
            //优惠劵id
            exchangeCode.setExchangeTargetId(coupon.getId());
            //兑换码 兑换的截止时间，就是优惠卷领取的截止时间
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());
            list.add(exchangeCode);
        }

        //将兑换码保存db exchange_code 批量保存
        this.saveBatch(list);
    }
}
